#!/bin/bash
#
# Developed by Fred Weinhaus 2/13/2013 .......... revised 4/30/2015
#
# ------------------------------------------------------------------------------
# 
# Licensing:
# 
# Copyright © Fred Weinhaus
# 
# My scripts are available free of charge for non-commercial use, ONLY.
# 
# For use of my scripts in commercial (for-profit) environments or 
# non-free applications, please contact me (Fred Weinhaus) for 
# licensing arrangements. My email address is fmw at alink dot net.
# 
# If you: 1) redistribute, 2) incorporate any of these scripts into other 
# free applications or 3) reprogram them in another scripting language, 
# then you must contact me for permission, especially if the result might 
# be used in a commercial or for-profit environment.
# 
# My scripts are also subject, in a subordinate manner, to the ImageMagick 
# license, which can be found at: http://www.imagemagick.org/script/license.php
# 
# ------------------------------------------------------------------------------
# 
####
#
# USAGE: colorglow -c coords [-a strength] [-s extent] [-f fuzzval] 
# [-l lightness] [h hue] infile outfile
# 
# USAGE: colorglow [-help]
# 
# OPTIONS:
# 
# -c     coords       coordinates for locating glow region; comma separate 
#                     pair of integers within the image
# -s     strength     strength (intensity) of glow; float>=0; default=100
# -e     extent       extent of glow; float>=0; default=5
# -f     fuzzval      fuzzval for locating glow region; 0<=float<=100;
#                     default=20
# -l     lightness    percent change in lightness of glow color; 
#                     float>=0; default=0
# -h     hue          percent change in hue of glow color; 
#                     -100<=float<=100; default=0
# 
###
# 
# NAME: COLORGLOW 
# 
# PURPOSE: To apply color glow effect to an image.
# 
# DESCRIPTION: COLORGLOW applies color glow effect to an image. The user must 
# supply a set of x,y coordinates within the image to located a contiguous 
# region of color with some fuzz value tolerance. The color will be extracted 
# from those coordinates automatically.
# 
# 
# ARGUMENTS: 
# 
# -c coords ... COORDS is the set of x,y coordinates to locate a contiguous 
# region of color where the glow will be applied.
# 
# -s strength ... strength (intensity) of glow effect. Values are floats greater 
# or equal to 0. The default=100.
# 
# -e extent ... extent is the extenting extent of the glow. Values are 
# floats greater or equal to 0.  The default=5.
# 
# -f fuzzval ... FUZZVAL for extracting the contiguous region of color. Values 
# are floats between 0 and 100. The default=20.
# 
# -l lightness ... LIGHTNESS is the percent change in lightness of the glow 
# color. Values are floats greater or equal to 0. The default=0.
# 
# -h hue ... HUE is the percent change in hue of the glow 
# color. Values are floats between -100 and 100. The default=0.
# 
# NOTE: Results may vary with versions of IM prior to 6.7.7.8 due to color 
# space changes. One can get close by varying the arguments, typically 
# raising the strength to 150 and increasing extent by 1 or 2.
# 
# CAVEAT: No guarantee that this script will work on all platforms, 
# nor that trapping of inconsistent parameters is complete and 
# foolproof. Use At Your Own Risk. 
# 
######
# 

# set default values
coords=""			# coords for locating color
strength=100			# strength (intensity, attenuation); float>=0
extent=5			# extenting extent; float>=0
fuzzval=20			# fuzzval for floodfill; float 0 to 100
lightness=0			# percent increase in lightness; float>=0
hue=0				# percent increase in hue; float>=0


# set directory for temporary files
dir="."    # suggestions are dir="." or dir="/tmp"

# set up functions to report Usage and Usage with Description
PROGNAME=`type $0 | awk '{print $3}'`  # search for executable on path
PROGDIR=`dirname $PROGNAME`            # extract directory of program
PROGNAME=`basename $PROGNAME`          # base name of program
usage1() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^###/g;  /^#/!q;  s/^#//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}
usage2() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^######/g;  /^#/!q;  s/^#*//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}

getMinMax()
	{
	img="$1"
	# statistics computed as percent (of dynamic range) values
	if [ "$im_version" -ge "06030901" ]
		then 
		min=`convert $img -format "%[min]" info:`
		max=`convert $img -format "%[max]" info:`
		min=`convert xc: -format "%[fx:100*$min/quantumrange]" info:`
		max=`convert xc: -format "%[fx:100*$max/quantumrange]" info:`
	else
		data=`convert $img -verbose info:`
		min=`echo "$data" | sed -n 's/^.*[Mm]in:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
		max=`echo "$data" | sed -n 's/^.*[Mm]ax:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
		min=`convert xc: -format "%[fx:100*$min]" info:`
		max=`convert xc: -format "%[fx:100*$max]" info:`
	fi
	}

# function to report error messages
errMsg()
	{
	echo ""
	echo $1
	echo ""
	usage1
	exit 1
	}


# function to test for minus at start of value of second part of option 1 or 2
checkMinus()
	{
	test=`echo "$1" | grep -c '^-.*$'`   # returns 1 if match; 0 otherwise
    [ $test -eq 1 ] && errMsg "$errorMsg"
	}

# test for correct number of arguments and get values
if [ $# -eq 0 ]
	then
	# help information
   echo ""
   usage2
   exit 0
elif [ $# -gt 14 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		     -help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-c)    # get coords
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID COORDS SPECIFICATION ---"
					   checkMinus "$1"
					   coords=`expr "$1" : '\([0-9]*,[0-9]*\)'`
					   [ "$coords" = "" ] && errMsg "--- COORDS=$coords MUST BE A NON-NEGATIVE COMMA SEPARATED PAIR OF INTEGER VALUES (with no sign) ---"
					   ;;
				-s)    # get strength
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID STRENGTH SPECIFICATION ---"
					   checkMinus "$1"
					   strength=`expr "$1" : '\([.0-9]*\)'`
					   [ "$strength" = "" ] && errMsg "--- STRENGTH=$strength MUST BE A NON-NEGATIVE FLOAT VALUE (with no sign) ---"
					   ;;
				-e)    # get extent
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID EXTENT SPECIFICATION ---"
					   checkMinus "$1"
					   extent=`expr "$1" : '\([.0-9]*\)'`
					   [ "$extent" = "" ] && errMsg "--- EXTENT=$extent MUST BE A NON-NEGATIVE FLOAT (with no sign) ---"
					   ;;
				-f)    # get fuzzval
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID FUZZVAL SPECIFICATION ---"
					   checkMinus "$1"
					   fuzzval=`expr "$1" : '\([.0-9]*\)'`
					   [ "$fuzzval" = "" ] && errMsg "--- FUZZVAL=$fuzzval MUST BE A NON-NEGATIVE FLOAT VALUE (with no sign) ---"
					   test1=`echo "$fuzzval < 0" | bc`
					   test2=`echo "$fuzzval > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- FUZZVAL=$fuzzval MUST BE A FLOAT BETWEEN 0 AND 100 ---"
					   ;;
				-l)    # get lightness
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID LIGHTNESS SPECIFICATION ---"
					   checkMinus "$1"
					   lightness=`expr "$1" : '\([.0-9]*\)'`
					   [ "$lightness" = "" ] && errMsg "--- LIGHTNESS=$lightness MUST BE A NON-NEGATIVE FLOAT VALUE (with no sign) ---"
					   ;;
				-h)    # get hue
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID HUE SPECIFICATION ---"
					   #checkMinus "$1"
					   hue=`expr "$1" : '\([-.0-9]*\)'`
					   [ "$hue" = "" ] && errMsg "--- HUE=$hue MUST BE A NON-NEGATIVE FLOAT VALUE (with no sign) ---"
					   test1=`echo "$hue < -100" | bc`
					   test2=`echo "$hue > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- HUE=$hue MUST BE A FLOAT BETWEEN -100 AND 100 ---"
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
		     	 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
	#
	# get infile and outfile
	infile="$1"
	outfile="$2"
fi

# test that infile provided
[ "$infile" = "" ] && errMsg "--- NO INPUT FILE SPECIFIED ---"

# test that outfile provided
[ "$outfile" = "" ] && errMsg "--- NO OUTPUT FILE SPECIFIED ---"


# set up temporary files
tmpA1="$dir/colorglow_A_$$.mpc"
tmpA2="$dir/colorglow_A_$$.cache"
trap "rm -f $tmpA1 $tmpA2;" 0
trap "rm -f $tmpA1 $tmpA2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpA2; exit 1" ERR

# read input image
convert -quiet "$infile" +repage "$tmpA1" ||
	echo  "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE  ---"


# get im_version
im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d; s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`


: <<COMMENT
# unused as explained above
# get im version
im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d; s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`

# colorspace RGB and sRGB swapped between 6.7.5.5 and 6.7.6.7 
# though probably not resolved until the latter
# then -colorspace gray changed to linear between 6.7.6.7 and 6.7.8.2 
# then -separate converted to linear gray channels between 6.7.6.7 and 6.7.8.2,
# though probably not resolved until the latter
# so -colorspace HSL/HSB -separate and -colorspace gray became linear
# but we need to use -set colorspace RGB before using them at appropriate times
# so that results stay as in original script
# The following was determined from various version tests using colorglow.
# with IM 6.7.4.10, 6.7.6.10, 6.8.2.10
# NOTE: I did not like the results when all versions are were made the same to match 6.7.4.10, 6.7.6.10
# I liked results much better from 6.8.2.10
# So must must note above that results may vary with older versions due to color space changes.
if [ "$im_version" -lt "06070607" -o "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace RGB"
else
	setcspace=""
fi
if [ "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace sRGB"
else
	setcspace=""
fi
COMMENT


# test for coordinates
if [ "$coords" != "" ]; then
	# test that coordinates are within the image
	wm1=`convert $tmpA1 -format "%[fx:w-1]" info:`
	hm1=`convert $tmpA1 -format "%[fx:h-1]" info:`
	xx=`echo "$coords" | cut -d, -f1`
	yy=`echo "$coords" | cut -d, -f2`
	# echo "wm1=$wm1; hm1=$hm1; xx=$xx; yy=$yy;"

	[ $xx -gt $wm1 ] && errMsg "--- X COORDINATE IS OUTSIDE IMAGE ---"
	[ $yy -gt $hm1 ] && errMsg "--- Y COORDINATE IS OUTSIDE IMAGE ---"


	# get color at coords
	color=`convert $tmpA1 -format "%[pixel:u.p{$coords}]" info:`
	# echo "color=$color;"
else
	errMsg "--- NO COORDINATES SPECIFIED ---"
fi


# convert lightness to modulate format from percent change
lightness=`convert xc: -format "%[fx:$lightness+100]" info:`
#echo "lightness=$lightness;"

# convert hue to modulate format from percent change
hue=`convert xc: -format "%[fx:$hue+100]" info:`
#echo "hue=$hue;"


# convert strength to fraction
strength=`convert xc: -format "%[fx:$strength/100]" info:`
#echo "strength=$strength;"

# set up floodfill
if [ "$im_version" -ge "07000000" ]; then
	matte_alpha="alpha"
else
	matte_alpha="matte"
fi


# get mask of color region and blur and apply strength
# apply as mask to overlay white
convert $tmpA1 \
	\( -clone 0 -fill $color -colorize 100% -modulate $lightness,100,$hue \) \
	\( -clone 0 -blur 0x1 -fuzz $fuzzval% -fill none -draw "$matte_alpha $coords floodfill" \
		-channel rgba -fill black +opaque none -fill white -opaque none -blur 0x$extent \
		-auto-level -evaluate multiply $strength  \) \
	-compose over -composite "$outfile"


exit 0

